﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.ObjectBuilder;
using WPFCABShell.Shell.Interface.Services.Options;

namespace WPFCABShell.Shell.Options
{
	public partial class OptionsView : IOptionsView
	{
		public static readonly DependencyProperty PresenterProperty = DependencyProperty.Register("Presenter",
			typeof(OptionsPresenter),
			typeof(OptionsView),
			new FrameworkPropertyMetadata(Presenter_Changed));

		[CreateNew]
		public OptionsPresenter Presenter
		{
			get
			{
				return GetValue(PresenterProperty) as OptionsPresenter;
			}
			set
			{
				SetValue(PresenterProperty, value);
			}
		}

		object IOptionsView.OptionsSite
		{
			get
			{
				return _optionsSiteTreeView;
			}
		}

		public OptionsView()
		{
			InitializeComponent();
		}

		void IOptionsView.Closed(bool dialogResult)
		{
			if (dialogResult)
			{
				Presenter.ApplyChanges();
			}
			else
			{
				Presenter.RevertChanges();
			}

			if (_optionsSiteTreeView.SelectedItem != null)
			{
				//either I'm losing it, or there really is no easier way to clear the selection [yep, tried Items.MoveCurrentTo(null)]
				TreeViewItem treeViewItem = _optionsSiteTreeView.ItemContainerGenerator.ContainerFromItem(_optionsSiteTreeView.SelectedItem) as TreeViewItem;
				Debug.Assert(treeViewItem != null);
				treeViewItem.IsSelected = false;
			}
		}

		private Window GetWindow()
		{
			DependencyObject parent = Parent;

			while (parent != null && !(parent is Window))
			{
				parent = LogicalTreeHelper.GetParent(parent);
			}

			return parent as Window;
		}

		private static void Presenter_Changed(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
		{
			Debug.Assert(dependencyObject is OptionsView);

			if (e.NewValue != null)
			{
				Debug.Assert(e.NewValue is OptionsPresenter);
				(e.NewValue as OptionsPresenter).View = dependencyObject as OptionsView;
			}
		}

		private void _optionsSiteTreeView_SelectedItemChanged(object sender, EventArgs e)
		{
			Presenter.SelectOptions(_optionsSiteTreeView.SelectedItem as IOptions);
		}

		private void okButton_Click(object sender, RoutedEventArgs e)
		{
			GetWindow().DialogResult = true;
		}
	}
}
